package cl.whyem.springmvc.series.controller;

import cl.whyem.springmvc.series.form.Contact;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes
@RequestMapping("/contact")
public class ContactController {

    private static List<Contact> contactList = new ArrayList<Contact>();

    static {
        contactList.add(new Contact("juan", "perez", "jperez@mail.com", "123"));
        contactList.add(new Contact("juana", "gonzalez", "jgonzalez@mail.com", "321"));
    }

    @RequestMapping("/create")
    public ModelAndView createContact() {
        return new ModelAndView("contact", "command", new Contact());
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact") Contact contact, BindingResult result) {
        if (contact != null && StringUtils.hasText(contact.getFirstname()) && StringUtils.hasText(contact.getLastname())) {
            System.out.println("First Name: " + contact.getFirstname() + "Last Name: " + contact.getLastname());
            synchronized (contactList) {
                contactList.add(contact);
            }
        }
        return "redirect:list";
    }

    @RequestMapping("/list")
    public String showContacts(Model model) {
        model.addAttribute("contactList", contactList);
        return "contact_list";
    }

    // Metodos para AJAX //
}
